<?php
namespace App\Lib\Auth;

use App\MenuPermission;
use App\RoleMenuPermission;
use App\BaseDictionary;
use Auth;
use App\Lib\Auth\CurrentUserGroupTrait;

class UserProfileHelper
{
    use CurrentUserGroupTrait;

    public function user()
    {
        return Auth::user();
    }

    public function profile()
    {
        return session('user_profile');
    }

    public function userPermissions()
    {
        $profile = $this->profile();
        return $profile['group_permission'];
    }

    public static function routes()
    {
        $profile = session('user_profile');
        return $profile['routes'];
    }

    public function initProfile()
    {
        $user = Auth::user();

        $coregroups = [];
        $routes = [];

        if ($user->isSuper()) {
            $permissions = MenuPermission::with('route')
                ->whereIn('permission_type', [
                    MenuPermission::$PERMISSION_TYPE_TOP_NAVI,
                    MenuPermission::$PERMISSION_TYPE_MENU_GROUP,
                    MenuPermission::$PERMISSION_TYPE_MENU,
                ])
                ->orderBy('sort_order')
                ->get();

            $menuFuns = $this->constructMenuLevel($permissions);

            array_push($coregroups, [
                'current' => BaseDictionary::$KEY_YES,
                'group_id' => 0,
                'menus' => $menuFuns['functions'],
                'defaultMenu' => $menuFuns['defaultMenu'],
            ]);
        } else {
            $userGroups = $user->userGroups;

            foreach ($userGroups as $group) {
                //找到该用户所有的组织（根组织），比如某用户挂在某公司下的一个部门里
                //则根组织就是该部门的母公司
                $coregroup = $group->coreOrganization();

                //只有有效的组织才作处理，未生效或者禁用的组织不作处理
                if ($group->isActive()) {
                    $userGroupPerms = [
                        'current' => $group->pivot->is_primary_group,
                        'group_name' => $coregroup->name,
                        'group_id' => $coregroup->id,
                        'group_type' => $coregroup->group_type,
                    ];

                    //根据根用户组（组织）的id获得该用户在该组织下的所有角色id列表
                    //通过该角色id列表获得所有对应的权限和路由
                    $groupRoleIds = $user->roles()->where('group_id', $coregroup->id)->get()->pluck('id')->toArray();

                    $permissions = MenuPermission::with('route')
                        ->whereIn('id', RoleMenuPermission::select('permission_id')
                            ->whereIn('role_id', $groupRoleIds)
                            ->get()->pluck('permission_id')->toArray())
                        ->orderBy('sort_order')
                        ->get();

                    foreach ($permissions as $permission) {
                        if ($permission->route) {
                            if (!in_array($permission->route->code, $routes)) {
                                array_push($routes, $permission->route->code);
                            }
                        }
                    }

                    $menuFuns = $this->constructMenuLevel($permissions);
                    $userGroupPerms['menus'] = $menuFuns['functions'];
                    $userGroupPerms['defaultMenu'] = $menuFuns['defaultMenu'];

                    array_push($coregroups, $userGroupPerms);
                }
            }
        }

        session(['user_profile' => [
                'group_permission' => $coregroups,
                'routes' => $routes,
            ]
        ]);
    }

    public function getCurrentUserGroupId()
    {
        $userGroups = $this->userPermissions();

        foreach ($userGroups as $userGroup) {
            if ($userGroup['current'] == BaseDictionary::$KEY_YES) {
                return $userGroup['group_id'];
            }
        }

        return null;
    }

    public function getManagedGroups()
    {
        $user = $this->user();
        $currentUserGroupId = $this->getCurrentUserGroupId();

        if ($user->isSuper() && empty($currentUserGroupId)) {
            $currentGroup = $this->getRootInternalOrganization();

            if (isset($currentGroup)) {
                $currentUserGroupId = $currentGroup->id;
            }
        }

        if (!empty($currentUserGroupId)) {
            $managedGroups = $this->getAllManagedGroups($currentUserGroupId);
            $managedGroupIds = collect($managedGroups)->pluck('id')->toArray();

            return [
                'currentUserGroupId' => $currentUserGroupId,
                'managedGroups' => $managedGroups
            ];
        }

        return null;
    }

    /**
    * 构造多级menu树，顶部navigator->菜单栏的一级菜单组->菜单项目
    */
    private function constructMenuLevel($permissions)
    {
        $modules = $permissions->where('permission_type', MenuPermission::$PERMISSION_TYPE_TOP_NAVI);

        $functions = [];
        $defaultMenu = null;

        foreach ($modules as $module) {
            $menugroups = $permissions->where('parent_id', $module->id);

            $groups = [];
            foreach ($menugroups as $menugroup) {
                $menuItems = $permissions->where('parent_id', $menugroup->id);

                $menus = [];
                foreach ($menuItems as $menuItem) {
                    array_push($menus, [
                        'id' => $menuItem->id,
                        'name' => $menuItem->name,
                        'icon' => $menuItem->icon,
                        'method' => isset($menuItem->route)?$menuItem->route->method:'',
                        'route' => isset($menuItem->route)?$menuItem->route->route:'',
                        'auth_code' => isset($menuItem->route)?$menuItem->route->code:'',
                        'is_default' => $menuItem->is_default,
                        'module_id' => $module->id,
                    ]);

                    if ($menuItem->is_default == BaseDictionary::$KEY_YES) {
                        $defaultMenu = [
                            'id' => $menuItem->id,
                            'name' => $menuItem->name,
                            'icon' => $menuItem->icon,
                            'method' => isset($menuItem->route)?$menuItem->route->method:'',
                            'route' => isset($menuItem->route)?$menuItem->route->route:'',
                            'auth_code' => isset($menuItem->route)?$menuItem->route->code:'',
                            'module_id' => $module->id,
                        ];
                    }
                }

                if (count($menus) > 0) {
                    array_push($groups, [
                        'id' => $menugroup->id,
                        'name' => $menugroup->name,
                        'icon' => $menugroup->icon,
                        'method' => isset($menugroup->route)?$menugroup->route->method:'',
                        'route' => isset($menugroup->route)?$menugroup->route->route:'',
                        'auth_code' => isset($menugroup->route)?$menugroup->route->code:'',
                        'menus' => $menus
                    ]);
                }
            }

            if (count($groups) > 0) {
                array_push($functions, [
                    'id' => $module->id,
                    'name' => $module->name,
                    'icon' => $module->icon,
                    'method' => isset($module->route)?$module->route->method:'',
                    'route' => isset($module->route)?$module->route->route:'',
                    'auth_code' => isset($module->route)?$module->route->code:'',
                    'groups' => $groups
                ]);
            }
        }

        return [
            'functions' => $functions,
            'defaultMenu' => $defaultMenu,
        ];
    }
}
